<template>
  <div class="logon">
    <div class="logon-content">
      <!--      <img src="src/assets/logon.jpeg" />-->
      <div class="image"></div>
      <!--      <img src="@/assets/logon.jpeg" alt="图片缺失" />-->
      <el-form
        ref="account"
        class="account"
        :model="account"
        :rules="rules"
        label-position="right"
        label-width="auto"
      >
        <el-form-item prop="username">
          <el-autocomplete
            ref="username"
            v-model.trim="account.username"
            placeholder="请输入用户名"
            :fetchSuggestions="suggestAccounts"
            @select="selectAccount"
          >
            <template #default="that">
              <span class="username-suggestions">
                <div>{{ that.item.username }} == {{ that.item.password }}</div>
                <div @click.stop="removeAccountFromLocalAccounts(that.item)">
                  <i class="el-icon-remove"></i>
                </div>
              </span>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="account.password"
            placeholder="请输入密码"
          >
          </el-input>
        </el-form-item>

        <el-form-item class="logon-button-item">
          <el-button
            class="logon-button"
            type="primary"
            @click="accountSubmit()"
            >登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// import New from './components/New.vue';
import { staticViews, content } from "@/router";
const accountKey = "accounts";
import { auth } from "@/apis";
import store from "@/store";
export default {
  name: "Logon",
  components: {
    // New,Old,
  },
  props: {
    sampleP: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      sampleD: "value",
      account: {
        username: null,
        password: null,
      },
      accounts: [],

      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  computed: {
    // sampleC() {
    //     return this.sampleD+'--';
    // }
  },
  created() {},
  mounted() {
    // this.$refs.username.focus();
    this.initAccounts();
  },
  methods: {
    sampleM() {},
    initAccounts() {
      // 初始加载  取
      //  从持久化的浏览器localstorage 取出accounts相关的数据，解析赋值给accounts
      let r = window.localStorage.getItem(accountKey);
      //r要么是null 要么是字符串
      // if (typeof r === "Array")
      if (r) {
        let rr = JSON.parse(r);
        if (Array.isArray(rr)) {
          this.accounts = rr;
        } else {
          this.$notify.warning("意外情况：accounts不是数组");
          this.accounts = [];
        }
      } else {
        this.$notify.warning("不存在" + r);
        this.accounts = [];
      }
    },
    addAccountToLocalAccounts() {
      // 第二步 增加
      // const k = this.accounts.find(x=>x.username===this.account.username)
      const i = this.accounts.findIndex(
        (x) => x.username === this.account.username
      );
      // i=-1 代表没有找到 ，i= 0,1,2,代表找到后的下表
      if (i === -1) {
        // push 会从末尾加，导致最近使用的用户名在最下面
        this.accounts.unshift(this.account);
        // this.$notify.warning(JSON.stringify(this.accounts))
        // 同步到localstorage使用watch函数
        // window.localStorage.setItem(accountKey, JSON.stringify(this.accounts));
      } else {
        //  重名 找到了
        // this.accounts.splice(i, 1, this.account);
        this.accounts.splice(i, 1);
        this.accounts.unshift(this.account);
        // window.localStorage.setItem(accountKey, JSON.stringify(this.accounts));
      }
      // window.localStorage.setItem("accounts",JSON.stringify(this.accounts))
    },

    accountSubmit() {
      this.$refs.account.validate((valid) => {
        if (valid) {
          this.addAccountToLocalAccounts();
          /**   this.$http({
            method: "post",
            url: "/login",
            data: `username=${this.account.username}&password=${this.account.password}`,
          })*/
          auth.login(this.account.username, this.account.password).then(
            (res) => {
              //第0步 打印调试
              this.$message.warning(JSON.stringify(res.data));
              //第一步 提交到vue-store中
              //{"basicId":1,"usernameFk":"zhangjiu001",
              // "nickname":"张老九","lastLoginTime":"2021-10-18T10:33:33.943"}
              /*
              * const _userInfo = {
              username: null,
              nickname: "匿名用户",
              lastLoginTime: null,
              };
              * */
              const payload = {
                username: res.data.usernameFk,
                nickname: res.data.nickname,
                lastLoginTime: res.data.lastLoginTime,
              };
              this.$store.commit("loginSuccess", payload);

              // 第n步 做业务相关的初始化操作

              // this.$store.dispatch("getRoutesAll").then(() => {
              // this.$store.dispatch("getRoutesByCurrentUser").then(() => {
              //   this.$notify.warning(
              //     "正在添加动态路由..." + this.$store.state.routesForRouter
              //   );
              //   // this.$store.state.routesForRouter.forEach(x=>{
              //   //   this.$router.addRoute("Content",x)
              //   // })
              //   console.log("static", staticViews);
              //   console.log("dynamic", this.$store.state.routesForRouter);
              //   //动静合并
              //   content.children = [
              //     ...staticViews,
              //     ...this.$store.state.routesForRouter,
              //   ];
              //   // content.children = staticViews.concat(
              //   //   this.$store.state.routesForRouter
              //   //
              //   // );
              //   this.$router.addRoute(content);
              //   this.$store.commit("sureDynamicRoutesAdd");
              //
              //   console.log("=========所有路由 ", this.$router.getRoutes());
              // });
              // this.$store.dispatch("getLeaveTypeEnums");
              // this.$store.dispatch("getApplyStateEnums");
              // this.$store.dispatch("getAuditStateEnums");

              //最后一步 跳转页面

              this.$store.dispatch("appInit").then(() => {
                this.$nextTick(() => {
                  this.$router.push("/content");
                });
              });
            },
            (error) => {
              // this.$message.error(error.response.data)
            }
          );
        } else {
          this.$message.warning("验证不通过请重新填写表单");
        }
      });
    },
    suggestAccounts(input, callback) {
      if (!input) {
        callback(this.accounts);
      } else {
        let r = this.accounts.filter((x) => x.username.startsWith(input));
        callback(r);
      }
    },
    selectAccount(item) {
      this.account = JSON.parse(JSON.stringify(item));
    },
    removeAccountFromLocalAccounts(item) {
      // this.$message.warning("要删除？" + item.username);
      const key = this.accounts.findIndex((x) => x.username === item.username);
      //[1.3.5.7.9]
      // splice(2,3,100 ,2200)
      this.accounts.splice(key, 1);
      // this.$message.success("删除完毕"+JSON.stringify(this.accounts))
      this.$refs.username.getData(this.account.username);
      let s = this.$refs.username.suggestions;
      if (s.length === 0) {
        this.account.username = "";
        this.account.password = "";
        this.$refs.username.focus();
      }
      // window.localStorage.setItem(accountKey, JSON.stringify(this.accounts));
    },
  },
  watch: {
    // accounts(n, o) {
    //   // this.$message.success("将要更新localstorage里的accounts");
    //   window.localStorage.setItem(accountKey, JSON.stringify(this.accounts));
    // },
    accounts: {
      handler(n, o) {
        // this.$notify.success("将要更新localstorage里的accounts");
        window.localStorage.setItem(accountKey, JSON.stringify(this.accounts));
      },
      // immediate:true,
    },
    // sampleC(newValue, oldValue) {
    //
    // }
  },
};
</script>

<!--<style scoped>-->
<style lang="scss" scoped>
@import "src/styles";
.logon {
  //background-color: rgba(216, 139, 19, 0.14);
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.account {
  width: 300px;
  margin-left: 48px;
  margin-right: 48px;
}
.logon-button {
  width: 100%;
}
.logon-button-item {
  margin-top: 60px;
}
.logon-content {
  display: flex;
  align-items: center;
  //padding-right: 20px;
  box-shadow: 0px 20px 80px 0px rgba(0, 0, 0, 0.4);
  //img {
  //  width: 500px;
  //  margin-right: 30px;
  //}
}
.image {
  width: 500px;
  height: 500px;
  background-image: url("~@/assets/logon.jpeg");
  background-size: contain;
  background-repeat: no-repeat;
}
.username-suggestions {
  color: $--color-primary;
  font: italic bold 16px/28px "楷体";
  display: flex;
  justify-content: space-between;
}
.el-autocomplete {
  width: 100%;
}
</style>
